package com.hckjsec.common.utils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.time.DateFormatUtils;

/**
 * 时间工具类
 * 
 * @author cyt
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    public static String HH_MM = "HH:mm";

    public static String MM_DD = "MM-dd";

    public static String HH_MM_SS = "HH:mm:ss";
    
    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", 
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     * 
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     * 
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }
    
    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    public static String getYearMonthDaysfmStr2(String day) {
        if (day == null) return "";
        if (day.length() < 8) return "";
        String n = day.substring(0, 4);
        String y = day.substring(5, 7);
        String r = day.substring(8, 10);
        String s = day.substring(11, 13);
        //String f = day.substring(14, 16);
        return n + "年" + y + "月" + r + "日"+ s + "时";
    }

    /**
     * 获取过去或者未来 任意天内的日期数组
     * @param intervals      intervals天内
     * @return              日期数组
     */
    public static ArrayList<String> getPastList(int intervals ) {
        ArrayList<String> pastDaysList = new ArrayList<>();
        for (int i = intervals-1; i >= 0; i--) {
            pastDaysList.add(getPastDate(i));
        }
        return pastDaysList;
    }

    /**
     * 获取过去第几天的日期
     *
     * @param past
     * @return
     */
    public static String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        String result = parseDateToStr(YYYY_MM_DD,calendar.getTime());
        return result;
    }

    /**
     * 获取过去或者未来 任意天内的日期数组
     * @param intervals      intervals天内
     * @return              日期数组
     */
    public static ArrayList<String> getPastMonthList(int intervals ) {
        ArrayList<String> pastDaysList = new ArrayList<>();
        for (int i = intervals-1; i >= 0; i--) {
            pastDaysList.add(getPastMonth(i));
        }
        return pastDaysList;
    }
    /**
     * 获取过去第几月
     *
     * @param past
     * @return
     */
    public static String getPastMonth(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - past);
        String result = parseDateToStr(YYYY_MM,calendar.getTime());
        return result;
    }

    /**
     * 获取过去第几年list
     * @param intervals      intervals天内
     * @return              日期数组
     */
    public static ArrayList<String> getPastYearList(int intervals ) {
        ArrayList<String> pastDaysList = new ArrayList<>();
        for (int i = intervals-1; i >= 0; i--) {
            pastDaysList.add(getPastYeat(i));
        }
        return pastDaysList;
    }
    /**
     * 获取过去第几年
     *
     * @param past
     * @return
     */
    public static String getPastYeat(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) - past);
        String result = parseDateToStr(YYYY,calendar.getTime());
        return result;
    }

    /**
     * 获取某年第一天日期
     * @param year 年份
     * @return Date
     */
    public static Date getYearFirst(int year){
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
        return currYearFirst;
    }

    /**
     * 获取某年最后一天日期
     * @param year 年份
     * @return Date
     */
    public static Date getYearLast(int year){
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
        Date currYearLast = calendar.getTime();
        return currYearLast;
    }

    /**
     * 得到当前日期的下一天的日期
     *
     * @param curday
     */
    public static String getNextDayStr(String curday) {
        Date date = dateTime(YYYY_MM_DD,curday);
        return parseDateToStr(YYYY_MM_DD,new Date(date.getTime() + 24 * 3600 * 1000));
    }
    /**
     * 通过字符中日期得到该日期是当前星期中的星期几
     *
     * @param curday
     */
    public static int getCurWeekDayByStr(String curday) {
        try {
            Date date = dateTime(YYYY_MM_DD,curday);
            Calendar rightNow = Calendar.getInstance();
            rightNow.setTime(date);
            return rightNow.get(Calendar.DAY_OF_WEEK);
        }
        catch (Exception e) {
            return 1;
        }
    }

    /**
     * 通过秒数获取相隔时间
     *
     * @param curday
     */
    public static String getIntervalStr(Long seconds) {
        seconds = Math.abs(seconds);//绝对值
        int day = (int) TimeUnit.SECONDS.toDays(seconds);
        long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
        long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
        long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);
        StringBuilder Str = new  StringBuilder();
        if (day > 0){
            Str.append(day +"天");
        }
        if (hours > 0){
            Str.append(hours +"时");
        }
        if (minute > 0){
            Str.append(minute +"分");
        }
        if (second > 0){
            Str.append(second +"秒");
        }
        return Str.toString();
    }


    /**
     * 比较两个日期大小
     *
     * @param curday
     */
    public static boolean compareStrDate(String oldDate,String date,String format){
        boolean flag = false;
        try {
            SimpleDateFormat sdf=new SimpleDateFormat(format);
            Date bt=sdf.parse(oldDate);
            Date et=sdf.parse(date);
            if (bt.before(et)){
                //表示bt小于et
                flag = true;
            }else{
                //反之
                flag = false;
            }
        }catch (Exception e){
            flag = false;
        }
        return flag;
    }

    /**
     * 获取某月的最后一天 如201712结果为2017-12-30
     * @param year
     * @param month
     * @return
     */
    public  static String getLastday(String year,String month){
        LocalDate firstDayOfCurrentDate = LocalDate.of(Integer.parseInt(year), Integer.parseInt(month), 1);
        LocalDate lastDayOfCurrentDate = firstDayOfCurrentDate.with(TemporalAdjusters.lastDayOfMonth());
        return lastDayOfCurrentDate.toString();
    }


    /**
     * 判断当前时间是否在[startTime, endTime]区间，注意时间格式要一致
     *
     * @param nowTime 当前时间
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     * @author jqlin
     */
    public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);
        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);
        Calendar end = Calendar.getInstance();
        end.setTime(endTime);
        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        String  old = "2022-01";
        String  date = "2022-02";

        System.out.println(compareStrDate(old,date,YYYY_MM));
    }
}
